const Survey = require('../models/Survey');
const fs = require('fs').promises;
const path = require('path');

class SurveyController {
    constructor() {
        this.surveyModel = new Survey();
    }

    // 获取随机问卷
    async getRandomSurvey(req, res) {
        try {
            const survey = await this.surveyModel.getRandomSurvey();
            
            if (!survey) {
                return res.status(404).json({
                    success: false,
                    message: '暂无可用问卷'
                });
            }

            res.json({
                success: true,
                data: survey
            });
        } catch (error) {
            console.error('获取随机问卷失败:', error);
            res.status(500).json({
                success: false,
                message: `获取随机问卷失败: ${error.message}`
            });
        }
    }

    // 根据ID获取问卷
    async getSurveyById(req, res) {
        try {
            const { id } = req.params;
            const survey = await this.surveyModel.getSurveyById(id);
            
            if (!survey) {
                return res.status(404).json({
                    success: false,
                    message: '问卷不存在或已停用'
                });
            }

            // 读取问卷文件内容
            const filePath = path.join(__dirname, '../public/suverys', survey.file_name);
            let fileContent = '';
            
            try {
                fileContent = await fs.readFile(filePath, 'utf-8');
            } catch (fileError) {
                console.warn(`无法读取问卷文件: ${survey.file_name}`);
            }

            res.json({
                success: true,
                data: {
                    ...survey,
                    content: fileContent
                }
            });
        } catch (error) {
            console.error('获取问卷详情失败:', error);
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }

    // 提交问卷回答
    async submitSurveyResponse(req, res) {
        try {
            const { studentId, surveyId, responses, completionTime } = req.body;

            // 验证必要参数
            if (!studentId || !surveyId || !responses) {
                return res.status(400).json({
                    success: false,
                    message: '缺少必要参数：学生ID、问卷ID或回答内容'
                });
            }

            // 检查是否已经提交过
            const hasCompleted = await this.surveyModel.hasStudentCompletedSurvey(studentId, surveyId);
            if (hasCompleted) {
                return res.status(409).json({
                    success: false,
                    message: '您已经提交过此问卷，无法重复提交'
                });
            }

            // 收集元数据
            const metadata = {
                completionTime,
                ipAddress: req.ip || req.connection.remoteAddress,
                userAgent: req.get('User-Agent')
            };

            // 提交回答
            const result = await this.surveyModel.submitSurveyResponse(
                studentId,
                surveyId,
                responses,
                metadata
            );

            res.json({
                success: true,
                data: result,
                message: '问卷提交成功，感谢您的参与！'
            });
        } catch (error) {
            console.error('提交问卷失败:', error);
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }

    // 检查学生是否已完成问卷
    async checkSurveyCompletion(req, res) {
        try {
            console.log('检查问卷完成状态请求参数:', req.params);
            const { studentId, surveyId } = req.params;
            
            if (!studentId || !surveyId) {
                return res.status(400).json({
                    success: false,
                    message: '缺少必要参数：studentId 和 surveyId'
                });
            }
            
            const hasCompleted = await this.surveyModel.hasStudentCompletedSurvey(studentId, surveyId);
            
            res.json({
                success: true,
                data: {
                    hasCompleted,
                    studentId,
                    surveyId
                }
            });
        } catch (error) {
            console.error('检查问卷完成状态失败:', error);
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }

    // 获取问卷列表
    async getSurveyList(req, res) {
        try {
            const surveys = await this.surveyModel.getAllActiveSurveys();
            
            res.json({
                success: true,
                data: surveys
            });
        } catch (error) {
            console.error('获取问卷列表失败:', error);
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }

    // 获取问卷统计信息
    async getSurveyStats(req, res) {
        try {
            const { id } = req.params;
            const stats = await this.surveyModel.getSurveyStats(id);
            
            res.json({
                success: true,
                data: stats
            });
        } catch (error) {
            console.error('获取问卷统计失败:', error);
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }
}

module.exports = new SurveyController();